<template>
  <el-card>
    <el-form
      ref="spuFormRef"
      label-width="100px"
      :model="spuFormData"
      :rules="spuFormRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input
          placeholder="Spu名称"
          v-model="spuFormData.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择" v-model="spuFormData.tmId">
          <el-option
            :value="tm.id"
            :label="tm.tmName"
            v-for="tm in trademarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          placeholder="SPU描述"
          :rows="2"
          type="textarea"
          v-model="spuFormData.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuFormData.spuImageList"
          action="/app-dev/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          :limit="MAX_UPLOAD_IMG_LENGTH"
          :on-success="handleUploadSuccess"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible" width="340">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select placeholder="还有三个未选择">
          <!-- <el-select placeholder="还有三个未选择" v-model="saleAttrList"> -->
          <el-option
            :label="attr.name"
            :value="attr.id"
            v-for="attr in saleAttrList"
            :key="attr.id"
          ></el-option>
        </el-select>
        <el-button type="primary" :icon="Plus">添加销售属性</el-button>
        <el-table :data="[{}]">
          <el-table-column
            type="index"
            label="序号"
            width="60"
          ></el-table-column>
          <el-table-column prop="xxx" label="属性名"></el-table-column>
          <el-table-column prop="xxx" label="属性值名称列表"></el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button :icon="Delete" size="small"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <template v-slot="{ row }">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="emit('setIsShow', true)">取消</el-button>
        </template>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddSpu",
}
</script>

<script lang="ts" setup>
import { ref, defineEmits, onMounted, reactive } from "vue"
import { ElMessage } from "element-plus"
import { Plus, Delete } from "@element-plus/icons-vue"
import {
  getAllTrademarkListApi,
  getBaseSaleAttrListApi,
} from "@/api/product/spu"
import type {
  TrademarkList,
  BaseSaleAttrList,
} from "@/api/product/model/spuModel"
import type {
  UploadProps,
  UploadUserFile,
  FormRules,
  FormInstance,
} from "element-plus"
const emit = defineEmits(["setIsShow"])
const spuFormData = reactive({
  spuName: "",
  tmId: undefined,
  description: "",
  spuImageList: [],
  spuSaleAttrList: [],
})
const spuFormRules = reactive<FormRules>({
  spuName: [{ required: true, message: "请输入SPU名称", trigger: "blur" }],
  tmId: [{ required: true, message: "请选择品牌", trigger: "blur" }],
  description: [{ required: true, message: "请输入Spu描述", trigger: "blur" }],
  spuImageList: [{ required: true, message: "请至少上传一张图片" }],
})
// 表单验证
const spuFormRef = ref<FormInstance>()
const submitForm = () => {
  spuFormRef.value?.validate((valid) => {
    if (valid) {
      console.log("表单校验通过")
    }
  })
}
const handleUploadSuccess = () => {
  // 如果上传了两张以上图片，就不可能出现表单校验失败的错误信息，就不用清空了
  if (spuFormData.spuImageList.length > 1) return
  // 图片上传成功, 至少有一张图片
  spuFormRef.value?.clearValidate(["spuImageList"])
}

// loading图片相关
const fileList = ref<UploadUserFile[]>([
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "plant-1.png",
    url: "/images/plant-1.png",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "plant-2.png",
    url: "/images/plant-2.png",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "figure-1.png",
    url: "/images/figure-1.png",
  },
  {
    name: "food.jpeg",
    url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  },
  {
    name: "figure-2.png",
    url: "/images/figure-2.png",
  },
])
const dialogImageUrl = ref("")
const dialogVisible = ref(false)
const MAX_UPLOAD_IMG_LENGTH = 10
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const typeFiles = ["image/jpeg", "image/jpg", "image/png"]
  if (!typeFiles.includes(rawFile.type)) {
    ElMessage.error("上传图片格式必须是jpg或png!")
    return false // 不会上传图片
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传图片大小不能超过200kb!")
    return false
  }
  return true // 继续上传图片
}

const trademarkList = ref<TrademarkList>([])
const saleAttrList = ref<BaseSaleAttrList>([])
// 分两次请求， 不会阻塞代码运行
onMounted(async () => {
  trademarkList.value = await getAllTrademarkListApi()
})
onMounted(async () => {
  saleAttrList.value = await getBaseSaleAttrListApi()
})
</script>

<style scoped></style>
